<template>
  <div class="app-container">


    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <div class="flex input-height">
        <div class="label" v-if="deptId==101">位置：</div>  
        <div class="align-center" v-if="deptId==101">
          <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
            class="margin-right" placeholder="请选择收费站" check-strictly  @change="bindChangeTree($event,'deptId')" />
        </div>
        <div class="label">时间：</div>
        <div class="align-center">
          <el-radio-group v-model="cycleRadio" @change="bindchangeDate" class="margin-right">
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="season">本季</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
          <el-date-picker style="margin-right:8px" v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            @change="bindChangeAllDate" />
        </div>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['audit:plan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['audit:plan:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column label="序号" align="center" type="index" width="65" />
      <el-table-column label="月份" align="center" prop="month">
      </el-table-column>
      <el-table-column label="收费站" align="center" prop="deptName" />
      <el-table-column label="计划文件" align="center" prop="planPath">
        <template #default="scope">
          <el-button link type="primary" icon="View" v-if="scope.row.planPath" @click="previewFun(scope.row.planPath)">
            <span class="el-icon-document"> 计划文件</span> </el-button>
            <div v-else>暂未上传</div>
        </template>
      </el-table-column>
      <el-table-column label="计划上传人" align="center" prop="planUserName" />
      <!-- <el-table-column label="计划上传日期" align="center" prop="planDate" width="180">
      </el-table-column> -->
      <el-table-column label="工作总结" align="center" prop="summaryName">
        <template #default="scope">
          <el-button link type="primary" icon="View" v-if="scope.row.summaryPath" @click="previewFun(scope.row.summaryPath)">
            <span class="el-icon-document"> 总结文件</span> </el-button>
            <div v-else>暂未上传</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="总结上传日期" align="center" prop="summaryDate" width="180">
      </el-table-column> -->
      <el-table-column label="总结上报人" align="center" prop="summaryUserName" />

      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row,1)" v-hasPermi="['audit:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="UploadFilled" @click="handleUpdate(scope.row,2)" v-hasPermi="['audit:plan:edit']">工作总结上传</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['audit:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改稽核计划对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="收费站" prop="deptId">
              <el-tree-select style="width:100%" class="inputDeep" v-model="form.deptId" :data="deptOptions" @node-click="handleNodeClick($event,'queryParams')"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择" check-strictly clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划年月" prop="yearMonth">
              <el-date-picker style="width:100%" class="inputDeep" clearable v-model="form.yearMonth" type="month" value-format="YYYY-MM" placeholder="请选择">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEdit">
            <el-form-item label="计划文件" prop="planPath" label-width="120px" >
              <file-upload v-model="form.planPath" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作总结" prop="summaryPath" v-if="isEdit">
              <file-upload v-model="form.summaryPath" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="5"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc"  />
  </div>
</template>

<script setup name="Plan">
import moment from 'moment'
import Viewer from "@/components/Custom/viewer.vue";
import { deptTreeSelect } from "@/api/system/user";
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/charge/plan";
import useUserStore from '@/store/modules/user'


const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { audit_dead_date } = proxy.useDict('audit_dead_date');
const planList = ref([]);
const userStore = useUserStore()
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const cycleRadio = ref('month')
const deptOptions = ref([])
const deptId = ref()
const userId = ref()
const userName = ref()
const dateSection = ref([])
const isEdit = ref(false)
const dialogDoc = ref(false)
const fileViewerRef = ref()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId:""
  },
  rules: {
    deptId: [
      { required: true, message: '收费站不能为空', trigger: 'blur' },
    ],
    yearMonth: [
      { required: true, message: '计划年月不能为空', trigger: 'blur' },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查询稽核计划列表 */
function getList() {
  loading.value = true;
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
function handleNodeClick(data) {
  form.value.deptId = data.id;
}
// 表单重置
function reset() {
  form.value = {
    id: null,
  };
  proxy.resetForm("planRef");
}
const bindChangeAllDate=(val)=>{  
  dateSection.value=[moment(val[0]).format("YYYY-MM-DD"),moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  start()
  queryParams.value.deptId=deptId.value;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  // 判断是否在上传时间内
  // let endDate=Number(audit_dead_date.value[0].value);
  // let month=moment().format('YYYY-MM');
  // let endDay=month+'-'+(endDate<10?'0'+endDate:endDate)
  // let day=moment().format('YYYY-MM-DD');
  // let isFlag=moment(day).isBetween(month+'-01',(moment(endDay).isValid()?endDay:moment().endOf('month').format('YYYY-MM-DD')), null, '[]')

  // if(isFlag){
    isEdit.value = false;
  form.value = { deptId: deptId.value }
  open.value = true;
  title.value = "添加稽核计划";
  // }else{
  //   proxy.$modal.msgError("本月计划请在"+endDate+"号之前提交");
  // }

}

/** 修改按钮操作 */
function handleUpdate(row,type) {
  reset();
  
  const _id = row.id || ids.value
  getPlan(_id).then(response => {
    form.value = response.data;
    // let date = form.value.year + "-" + (Number(form.value.month < 10) ? '0' + form.value.month : form.value.month);
    // form.value.month = date;
    open.value = true;
    if(type==1){
      isEdit.value=false
    }else{
      isEdit.value = true;
    }
    title.value = type==1?"修改稽核计划":"上报总结";
  });
}

/** 提交按钮 */
function submitForm() {
  let endDate=Number(audit_dead_date.value[0].value)
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      // if (form.value.month.indexOf('-') != -1) {
      //   let date = form.value.month.split("-")
      //   form.value.year = date[0]
      //   form.value.month = date[1]
      // }

      if (form.value.id != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("上传成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then(response => {
          // proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          proxy.$modal.msgSuccess("新增成功，请于下月"+endDate+"号之前上传工作总结");
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除稽核计划编号为"' + _ids + '"的数据项？').then(function () {
    return delPlan(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
const bindchangeDate = (val) => {
  let date = new Date();
  let year = date.getFullYear();
  let params = {}
  if (val == 'day') {
    params.startDate = moment().format("YYYY-MM-DD")
    params.endDate = moment().format("YYYY-MM-DD");
  } else if (val == 'week') {
    params.startDate = moment().startOf('week').format('YYYY-MM-DD');
    params.endDate = moment().endOf('week').format('YYYY-MM-DD')
  } else if (val == 'month') {
    params.startDate = moment().startOf('month').format('YYYY-MM-DD');
    params.endDate = moment().endOf('month').format('YYYY-MM-DD')
  } else if (val == 'season') {
    let startQuarter = moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()).format('YYYY-MM-DD');
    let endQuarter = moment(moment().quarter(moment().quarter()).endOf('quarter').valueOf()).format('YYYY-MM-DD');
    params.startDate = startQuarter
    params.endDate = endQuarter
  } else {
    params.startDate = year + '-01-01'
    params.endDate = year + '-12-31'
  }
  dateSection.value = [moment(params.startDate).format("YYYY-MM-DD"), moment(params.endDate).format("YYYY-MM-DD")]
  queryParams.value = { ...queryParams.value, ...params,deptId:deptId.value }; getList()


}
const bindChangeTree = (val, name) => {
  queryParams.value[name]= val;
}
// 预览
// const previewFun = (file) => {
//   dialogDoc.value = true;
//   let data = {};
//   // 上传过的文件组成完成的网络路径
//   if (file) {
//     data.src = `${baseUrl}${file}`;
//   }

//   const arr=file.split(".");
//   const suffix = arr[arr.length-1];
//   if (suffix == "docx" || suffix == "doc") {
//     fileViewerRef.value?.viewDocx(data);
//   } else if (suffix == "xlsx" || suffix == "xls") {
//     fileViewerRef.value?.viewXlsx(data);
//   } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
//     fileViewerRef.value?.viewImg(data);
//   } else if (suffix == "pdf") {
//     fileViewerRef.value?.viewPdf(data);
//   }
// };
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file&&file.indexOf(',')==-1) {
    data.src = `${baseUrl}${file}`;
  }else if(file&&file.indexOf(',')!=-1){
    let src=file.split(',');
    let srcArr=[]
    src.forEach(item=>{srcArr.push(`${baseUrl}${item}`)})
    data.src = srcArr.join(',');
    file=srcArr[0]
  }

  const arr=file.split(".");
  const suffix = arr[arr.length-1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data,'稽核计划');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
/** 导出按钮操作 */
function handleExport() {
  proxy.download('audit/plan/export', {
    ...queryParams.value
  }, `稽核计划_${new Date().getTime()}.xlsx`)
}
const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;
      userId.value = res.user.userId;
      userName.value = res.user.userName;
      form.value.deptId = deptId.value
      queryParams.value.deptId=deptId.value;
      getList();
    }

  })
}

const start = () => {
  let strDate = moment().startOf('month').format('YYYY-MM-DD');
  let endDate = moment().endOf('month').format('YYYY-MM-DD')
  dateSection.value = [strDate, endDate];
  queryParams.value.startDate = strDate;
  queryParams.value.endDate = endDate;
}

start()
getDeptId()
getDeptTree()
// 
</script>


<style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.flex .label {
  color: #333;
  font-size: 14px;
}
.margin-right-lg {
  margin-right: 32px;
}
.margin-right {
  margin-right: 8px;
}
.align-center {
  display: flex;
  align-items: center;
}
.margin-top {
  margin-top: 20px;
}



</style>
